package com.example.interceptors;

import com.alibaba.fastjson2.JSON;
import com.example.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//用于拦截http请求
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate template;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try{
            ValueOperations<String, String> operations = template.opsForValue();
            String redisToken = operations.get(token);
            if(redisToken == null){
                throw new RuntimeException();
            }
//        将jwt令牌值转化为用户数据
            Map<String, Object> data = JwtUtil.parseToken(token);
            String jsonString = JSON.toJSONString(data);
            template.opsForValue().set("data", jsonString);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
